package com.ruoyi.api.util.wx;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

import com.ruoyi.common.utils.Md5Utils;

public class DownloadPicFromURL {
	
	/**
     * 默认文件类型jpg
     */
    public static final String IMAGE_JPG_EXTENSION = ".jpg";

    private static int counter = 0;
	
	public static void main(String[] args) {
		String url = "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0";
		String path = "d:/pic.jpg";
		downloadPicture(url);
	}

	// 链接url下载图片
	public static String downloadPicture(String headPic) {
		String fileName = Md5Utils.hash("wx"+String.valueOf(new Random().nextInt(8999999) + 1000000) + System.nanoTime() + counter++) + IMAGE_JPG_EXTENSION;
		String path = "/home/find/web/img/"+fileName;
		URL url = null;
		try {
			url = new URL(headPic);
			DataInputStream dataInputStream = new DataInputStream(url.openStream());

			FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
			return fileName;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
